package de.herberlin.webapp.core;

import javax.servlet.http.HttpServletRequest;

import de.herberlin.webapp.db.Service;
import de.herberlin.webapp.text.Page;
import de.herberlin.webapp.user.User;

/**
 * Functions.java
 *
 * Created on 28. Oktober 2007, 22:10
 *
 * @author herberlin
 */
public abstract class Functions {
    
    //private static Log logger=LogFactory.getLog(Functions.class);
    
    public static Page getPage(HttpServletRequest req) {
        
        String pageId=req.getServletPath();
        if (pageId==null) {
            pageId="index";
        }
        if (pageId.lastIndexOf(".")>0) {
            pageId=pageId.substring(0,pageId.lastIndexOf("."));
        }
        if (pageId.startsWith("/")) {
            pageId=pageId.substring(1);
        }
        pageId=pageId.replaceAll("/","_");
        Page page=Service.getItem(Page.class,pageId);
        
        if (page==null && isAdmin(req)) {
            page=new Page();
            page.setHeadline("Headline");
            page.setId(pageId);
            page.setText("Enter text here..");
            page.setHorizontalMenu(1);
            page.setVerticalMenu(1);
            Service.persist(page);
        }
        
        return page;
    }
    
    public static  boolean isAdmin(HttpServletRequest req) {
    	
		User user=(User)req.getSession().getAttribute(User.MY_SCOPE_NAME);
		if (user==null || !user.isLoggedIn()) {
			return false;
		} else {
			return true;
		}
    }
    
    /**
     * Replace all new-lines by br-html tag
     */
    public static String nl2Br(String st) {
        if (st !=null) {
            st=st.replaceAll("\\n","<br/>");
        }
        return st;
    }
}
